# -*- coding: utf-8 -*-
import sqlalchemy as sa
from wtforms_alchemy import ModelForm

from bopress.hook import add_action, add_submenu_page
from bopress.model import Users
from bopress.orm import SessionFactory, pk
from bopress.ui import AbstractListTableDataProvider
from bopress.user import ObjectPermissionChecker, add_data_capability, add_role_capability, remove_perms_for_bulk_delete, registry
from bopress.utils import Utils
from userobjectermissionsdemo.model import Posts

__author__ = 'yezang'


def delete_event_demo():
    s = SessionFactory.session(use_evt=True)
    try:
        s.query(Posts).filter(Posts.post_id == 6).delete()
        remove_perms_for_bulk_delete(s, Posts, [6])
        s.commit()
    except Exception as e:
        print(e)
        s.rollback()


class UserForm(ModelForm):
    class Meta:
        model = Users


class PostForm(ModelForm):
    class Meta:
        model = Posts


def data(handler):
    # delete_event_demo()
    s = SessionFactory.session()
    p = Posts()
    p.post_id = pk()
    p.title = "Configuration 1"
    p.content = "After installation we can prepare our project for object permissions handling. " \
                "In a settings module we need to add guardian to INSTALLED_APPS"
    p.pubdate = Utils.current_datetime()
    s.add(p)
    s.commit()
    # 角色权限
    chk = ObjectPermissionChecker()
    chk.assign(['r_edit_post', 'r_delete_post'], p)
    # 用户权限
    chk2 = ObjectPermissionChecker(2)
    chk2.assign(['add_post', 'list_post', 'edit_post', 'delete_post'], p)

    b1 = chk2.has_perms('edit_post', p)
    b2 = chk2.has_perms('edit_post', p, use_role=True)

    print(b1, b2)

    users = chk2.get_users(p)
    s = SessionFactory.session()
    r = s.query(users)
    print(r.value(users.c.user_id))

    chk2.remove_perms(["r_delete_post"], p, use_role=True)

    users_set = chk2.get_objects(["edit_post", "r_edit_post"], Posts)
    z = s.query(Posts.title, Posts.content) \
        .select_from(users_set).outerjoin(Posts, Posts.post_id == users_set.c.object_id) \
        .all()
    print(z)
    handler.render_json(p.post_id)


class DemoListTableDataProvider(AbstractListTableDataProvider):
    def primary_key(self, handler):
        return "post_id"

    def data(self, handler, params):
        s = SessionFactory.session()
        search_text = params['search']['value']
        search_text = "%{0}%".format(search_text)
        q = s.query(Posts)
        if search_text:
            q = q.filter(sa.or_(Posts.title.like(search_text), Posts.content.like(search_text)))
        q = self.paginate(q, params["start"], params["length"])
        count_q = s.query(Posts)
        if search_text:
            count_q = count_q.filter(sa.or_(Posts.title.like(search_text), Posts.content.like(search_text)))
        num = count_q.count()
        items = list()
        for r in q.all():
            items.append({"post_id": r.post_id, "title": r.title, "content": r.content})
        self.render_json(handler, items, num, num, params)

    def columns(self, handler):
        return ["title", "content"]

    def column_titles(self, handler):
        return ["标题", "内容"]

    def column_render_cb(self):
        return "my_custom_col_render"

    def orderable_columns(self, handler):
        return ["title"]

    def forms(self, handler):
        return [UserForm(), PostForm()]

    def form_titles(self, handler):
        return ["用户", "帖子"]

    def dropdown_actions(self, handler):
        return [("approve", "Approve the project")]

    def row_actions(self, handler):
        return {"title": [("approve", "Approve")]}

    def form_layouts(self, handler):
        layouts = {
            0: (
                '登录账号',
                ('user_login', 'user_pass'),
                '基本资料',
                ('user_nicename', 'user_email', 'user_mobile_phone', (2, 2, 8)),
                '其它信息',
                ('user_url', 'user_registered', 'user_activation_key', 'user_status'),
                '描述',
                ('display_name',)
            )
        }
        return layouts


def init():
    add_data_capability("add_post", "Post", "新增文章")
    add_data_capability("list_post", "Post", "查看文章")
    add_data_capability("edit_post", "Post", "编辑文章")
    add_data_capability("delete_post", "Post", "删除文章")
    add_role_capability("edit_post", "Post", "修改文章")
    add_role_capability("delete_post", "Post", "移除文章")

    s = SessionFactory.session()

    # posts test data.
    if SessionFactory.object_num(Posts) == 0:
        posts_arr = list()
        for i in range(50):
            s = SessionFactory.session()
            p = Posts()
            p.post_id = pk()
            p.title = "标题 {0}".format(i)
            p.content = "After installation we can prepare our project for object permissions handling. "
            p.pubdate = Utils.current_datetime()
            posts_arr.append(p)
        s.add_all(posts_arr)
        s.commit()

    if SessionFactory.object_num(Users) == 1:
        for c in range(11):
            registry(Utils.random_str(), '123456', '{0}@bopress.com'.format(Utils.random_str()),
                     Utils.random_num(11), Utils.random_str(), Utils.random_str(), 1)


def page(current_screen):
    h = current_screen.handler
    h.render("userobjectermissionsdemo/tpl/uop.html",
             current_screen=current_screen,
             provider=DemoListTableDataProvider)


add_submenu_page("dev-example", "User Object Permissions Demo", "User Object Permissions Demo",
                 "user-object-permissions-demo", ["r_list_users"], page)
add_action("bo_init", init)
add_action("bo_api_get_user_object_permissions_demo", data)
